<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增评论</el-button>
      </div>
    </template>
    <el-table :load="state.loading" :data="state.tableData" tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="id" label="评价编号" width="100">
      </el-table-column>
      <el-table-column label="头像">
        <template #default="scope">
          <img style="width: 50px; height: 50px;" :key="scope.row.goodsId"
            :src="$filters.prefix(scope.row.introduceSign)" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="昵称">
      </el-table-column>
      <el-table-column prop="shareContent" label="评价内容">
      </el-table-column>
      <el-table-column label="评价图片">
        <template #default="scope">
          <img style="width: 100px; height: 100px;" :key="scope.row.goodsId" :src="scope.row.shareUrlList[0]"
            alt="评价主图">
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="时间">
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="info" @click="handleDetail(scope.row.id)">详情</el-button>
          <el-button type="primary" style="margin-right: 10px;" @click="handleEdit(scope.row.id)">修改</el-button>
          <el-button type="danger" style="margin-right: 10px;" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination background layout="total,prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
      :total="state.total" :page-size="state.pageSize" :current-page="state.currentPage" @current-change="changePage" />
    <el-dialog :title="state.title" v-model="state.visible" width="500px">
      <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="100px">
        <el-form-item label="头像" prop="introduceSign">
          <el-upload class="avatar-uploader" :action="state.uploadImgServer" accept="jpg,jpeg,png" :headers="{
            token: state.token
          }" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUrlSuccess">
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.form.introduceSign"
              :src="state.form.introduceSign" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input type="text" v-model="state.form.userName"></el-input>
        </el-form-item>
        <el-form-item label="商品" prop="goodsId">
          <el-select v-model="state.form.goodsId" placeholder="请选择" size="large" @change="selGood">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in state.goodsList" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="规格" prop="specId">
          <el-select v-model="state.form.specId" placeholder="请选择" size="large">
            <el-option :label="item.name" :value="item.id" v-for="item in state.specList" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="评价内容" prop="shareContent">
          <el-input type="textarea" :rows="4" v-model="state.form.shareContent"></el-input>
        </el-form-item>
        <el-form-item required label="图片" prop="shareUrlList">
          <el-upload v-model:file-list="state.form.shareUrlList" :action="state.uploadImgServer"
            accept="jpg,jpeg,png,mp3,mp4" :headers="{ token: state.token }" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleCarouselSuccess">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="state.type != 'detail'">
          <el-button @click="state.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" style="width: 100%;" alt="Preview Image" />
    </el-dialog>
  </el-card>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance, ref } from 'vue'
import axios from '@/utils/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CirclePlus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { localGet, uploadImgServer } from '@/utils'

const { proxy } = getCurrentInstance()

const app = getCurrentInstance()
const { goTop } = app.appContext.config.globalProperties
const router = useRouter()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10,// 分页大小
  data: {},
  role: '',
  title: '',
  visible: false,
  form: {
    userName: '',
    introduceSign: '',
    goodsId: '',
    specId: '',
    only: null,
    shareContent: '',
    shareType: '1',
    shareUrl: '',
    shareUrlList: []
  },
  type: 'add',
  goodsList: [],
  specList: []
})
const userDialog = ref(false)
onMounted(() => {
  getGoodList()
  getGoodArr()
  const userInfo = localGet('userInfo')
  if (userInfo) {
    state.role = userInfo.role
  }
})
const getGoodList = () => {
  state.loading = true
  axios.get('/getShareListOnAdmin', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      only: null
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
    goTop && goTop()
  })
}
const getGoodArr = () => {
  axios.get('/getMapGood').then(res => {
    state.goodsList = res
    console.log(state.goodsList)
  })
}
const selGood = () => {
  axios.get('/getMapSpec/' + state.form.goodsId).then(res => {
    state.specList = res
  })
}
const handleAdd = () => {
  state.type = 'add'
  state.title = '新增'
  state.form = {
    shareType: '1'
  }
  state.visible = true
}
const handleEdit = (id) => {
  state.type = 'edit'
  state.title = '编辑'
  axios.get('/getShareById/' + id).then(res => {
    state.form = res
    let list = []
    res.shareUrlList.forEach(item => {
      list.push({ url: item })
    })
    state.form.shareUrlList = list
  })
  state.visible = true
}
const handleDetail = (id) => {
  state.type = 'detail'
  state.title = '详情'
  axios.get('/getShareById/' + id).then(res => {
    state.form = res
    let list = []
    res.shareUrlList.forEach(item => {
      list.push({ url: item })
    })
    state.form.shareUrlList = list
  })
  state.visible = true
}
const handleCarouselSuccess = (val) => {
  state.form.shareUrl = state.form.shareUrl ? state.form.shareUrl + ',' + val.url : '' + val.url
}
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const handleUrlSuccess = (val) => {
  state.form.introduceSign = val.url || ''
}
const submitForm = () => {
  if (state.type == 'add') {
    axios.post('/insertUserShare', state.form).then(res => {
      ElMessage.success('新增成功')
      getGoodList()
      state.visible = false
    })
  } else {
    axios.post('/updateUserShare', state.form).then(res => {
      ElMessage.success('提交成功')
      getGoodList()
      state.visible = false
    })
  }
}
const sureShare = () => {
  proxy.$download('/getTaoBaoqQRCode', {
    goodsId: state.data.goodsId,
    goodsCoverImg: state.data.goodsCoverImg,
    originalPrice: state.data.originalPrice,
    sellingPrice: state.data.sellingPrice,
    goodsName: state.data.goodsName,
    userId: state.form.userId || ''
  }, `good_${new Date().getTime()}.jpg`)
  userDialog.value = false
}
const handleShare = (row) => {
  userDialog.value = true
  state.data = row
}
const handleDel = (id) => {
  ElMessageBox.confirm(
    '确认删除此项?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.get('/deleteUserShare/' + id).then(res => {
        console.log(res)
        ElMessage({
          message: '删除成功！',
          type: 'success',
        })
        getGoodList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const changePage = (val) => {
  state.currentPage = val
  getGoodList()
}
const handleStatus = (id, status) => {
  axios.put(`/goods/status/${status}`, {
    ids: id ? [id] : []
  }).then(() => {
    ElMessage.success('修改成功')
    getGoodList()
  })
}
</script>

<style scoped>
.good-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 30px;
}
</style>
